package cn.findviewbydream.service.impl;

import cn.findviewbydream.dao.PostMapper;
import cn.findviewbydream.entity.PostEntity;
import cn.findviewbydream.entity.UserEntity;
import cn.findviewbydream.enums.PostEnum;
import cn.findviewbydream.enums.SessionEnum;
import cn.findviewbydream.exception.PostException;
import cn.findviewbydream.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

/**********************************
 * 工程：cn.findviewbydream.service.impl
 * 作者：白雨濃 evil
 * 时间：17-6-2 下午1:56
 * 邮箱：evilbai@foxmail.com
 * 内容：贴子信息相关
 **********************************/
@Service
public class PostServiceImpl implements PostService
{
    private final PostMapper mapper;

    @Autowired
    public PostServiceImpl(PostMapper mapper)
    {
        this.mapper = mapper;
    }

    @Override
    public List<PostEntity> getPostList()
    {
        return mapper.selectPostList();
    }

    @Override
    public PostEntity getPost(int postId)
    {
        PostEntity entity = mapper.selectPost(postId);
        if (entity == null)
            throw new PostException(PostEnum.NULL_POST);

        return entity;
    }

    @Override
    public Boolean postPost(PostEntity entity, HttpSession session)
    {
        UserEntity user = (UserEntity) session.getAttribute(SessionEnum.USER.getKey());

        if (user == null)
            throw new PostException(PostEnum.NO_LOGIN);

        /*置入作者*/
        entity.setAuthor(user);

        int count;
        try
        {
            count = mapper.insertPost(entity);
        }
        catch (Exception e)
        {
            throw new PostException(PostEnum.UNKNOWN_ERROR, e);
        }
        return count == 1;
    }
}
